package com.wefiesta.app.http;


import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.wefiesta.app.MainActivity;
import com.wefiesta.app.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

/**
 * 
 * Login Task
 * 
 * @author jeonminho
 *
 */
public class LoginTask extends AsyncTask<String, Void, String> {

	private String TAG = "LoginTask";
	private ProgressDialog progressDialog;
	public Context mContext;
	public Activity activity;
	
	public LoginTask(Activity activity) {
		
		this.activity = activity; 
		this.progressDialog = new ProgressDialog(this.activity);
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();

		progressDialog.setTitle(R.string.login);
		progressDialog.setMessage("로그인 중입니다..");
		progressDialog.setCancelable(false);
		progressDialog.show();

	}

	@Override
	protected String doInBackground(String... params) {

		String resultCode = "";

		try {

			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost(params[0]);
			List<BasicNameValuePair> param = new ArrayList<BasicNameValuePair>();

			param.add(new BasicNameValuePair("userid", params[1]));
			param.add(new BasicNameValuePair("userpw", params[2]));

			UrlEncodedFormEntity ent = new UrlEncodedFormEntity(param,
					HTTP.UTF_8);
			post.setEntity(ent);
			HttpResponse responsePost = client.execute(post);
			HttpEntity resEntity = responsePost.getEntity();

			String responseValue = "";
			if (resEntity != null) {
				responseValue = EntityUtils.toString(resEntity);
			}

			JSONObject json = new JSONObject(responseValue);
			resultCode = json.getString("code");

		} catch (Exception e) {

			Log.e(TAG, e.getMessage());
		}

		return resultCode;

	}

	@Override
	protected void onPostExecute(String result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);

		if (progressDialog.isShowing()) {
			progressDialog.dismiss();
		}

		if (result.equals("0")) {
			this.activity.finish();
			Toast.makeText(mContext, R.string.login, Toast.LENGTH_SHORT).show();
			Intent intent = new Intent(mContext, MainActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			mContext.startActivity(intent);

		} else {

			Toast.makeText(mContext, R.string.loginfailed, Toast.LENGTH_SHORT).show();

		}
	}
}